#!/usr/bin/env python3
"""
数据库管理工具
Database Management Tool

提供Neo4j数据库的管理功能，包括初始化、备份、恢复等
Provides Neo4j database management features including initialization, backup, restore, etc.
"""

import os
import sys
import json
import logging
import argparse
from datetime import datetime
from typing import Dict, Any

# 添加项目根目录到系统路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_root)

from api.services.neo4j_service import neo4j_service
from api.config.database import Config

class DatabaseManager:
    """数据库管理器"""
    
    def __init__(self):
        self.setup_logging()
    
    def setup_logging(self):
        """设置日志"""
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            handlers=[
                logging.StreamHandler(),
                logging.FileHandler('database_manager.log', encoding='utf-8')
            ]
        )
    
    def check_connection(self) -> bool:
        """检查Neo4j连接"""
        try:
            status = neo4j_service.check_database_status()
            if 'error' in status:
                print(f"❌ Neo4j连接失败: {status['error']}")
                return False
            else:
                print("✅ Neo4j连接成功")
                return True
        except Exception as e:
            print(f"❌ Neo4j连接测试失败: {str(e)}")
            return False
    
    def show_status(self):
        """显示数据库状态"""
        print("="*60)
        print("📊 Neo4j数据库状态")
        print("="*60)
        
        if not self.check_connection():
            return False
        
        try:
            status = neo4j_service.check_database_status()
            
            if 'error' in status:
                print(f"❌ 获取状态失败: {status['error']}")
                return False
            
            print(f"数据库URI: {Config.NEO4J_URI}")
            print(f"用户名: {Config.NEO4J_USERNAME}")
            print(f"初始化状态: {'✅ 已初始化' if status.get('total_nodes', 0) > 0 else '❌ 未初始化'}")
            print()
            print("数据统计:")
            print(f"  总节点数: {status.get('total_nodes', 0)}")
            print(f"  疾病数: {status.get('diseases', 0)}")
            print(f"  症状数: {status.get('symptoms', 0)}")
            print(f"  药物数: {status.get('drugs', 0)}")
            print(f"  科室数: {status.get('departments', 0)}")
            print(f"  总关系数: {status.get('total_relationships', 0)}")
            
            return True
            
        except Exception as e:
            print(f"❌ 获取数据库状态失败: {str(e)}")
            return False
    
    def validate_data_files(self) -> bool:
        """验证数据文件"""
        print("="*60)
        print("🔍 验证数据文件")
        print("="*60)
        
        # 获取项目根目录
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        data_dir = os.path.join(project_root, 'api', 'data')
        files_to_check = {
            'medical_data.json': '医疗数据文件',
            'knowledge_graph.json': '知识图谱文件'
        }
        
        all_valid = True
        
        for filename, description in files_to_check.items():
            filepath = os.path.join(data_dir, filename)
            print(f"\n检查 {description}: {filepath}")
            
            if not os.path.exists(filepath):
                print(f"  ❌ 文件不存在")
                all_valid = False
                continue
            
            try:
                with open(filepath, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                # 基本结构验证
                if filename == 'medical_data.json':
                    diseases = data.get('diseases', [])
                    departments = data.get('departments', [])
                    print(f"  ✅ 包含 {len(diseases)} 个疾病, {len(departments)} 个科室")
                    
                elif filename == 'knowledge_graph.json':
                    nodes = data.get('nodes', [])
                    relationships = data.get('relationships', [])
                    print(f"  ✅ 包含 {len(nodes)} 个节点, {len(relationships)} 个关系")
                
            except json.JSONDecodeError as e:
                print(f"  ❌ JSON格式错误: {str(e)}")
                all_valid = False
            except Exception as e:
                print(f"  ❌ 验证失败: {str(e)}")
                all_valid = False
        
        if all_valid:
            print("\n✅ 所有数据文件验证通过")
        else:
            print("\n❌ 数据文件验证失败")
        
        return all_valid

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='医疗问答系统 - Neo4j数据库管理工具')
    parser.add_argument('--status', action='store_true', help='显示数据库状态')
    parser.add_argument('--check', action='store_true', help='检查数据库连接')
    parser.add_argument('--validate', action='store_true', help='验证数据文件')
    
    args = parser.parse_args()
    
    manager = DatabaseManager()
    
    success = True
    
    if args.check:
        success = manager.check_connection()
    elif args.status:
        success = manager.show_status()
    elif args.validate:
        success = manager.validate_data_files()
    else:
        # 默认显示状态和使用帮助
        print("医疗问答系统 - Neo4j数据库管理工具")
        print("\n使用帮助:")
        print("  python scripts/database_manager.py --status      # 显示数据库状态")
        print("  python scripts/database_manager.py --check       # 检查数据库连接")
        print("  python scripts/database_manager.py --validate    # 验证数据文件")
    
    sys.exit(0 if success else 1)

if __name__ == '__main__':
    main()